<?php

class Users_model extends Model {

    function Users_model() {
        parent::Model();
    }

    function setVal($options, $user) {
        $string = "<SetUser><login value=\"$user\" />";

        $setuser = array('login', 'ip', 'password', 'tariff', 'name', 'address', 'phone', 'email', 'note', 'userdata0', 'userdata1', 'userdata2', 'userdata3', 'userdata4', 'userdata5', 'userdata6', 'userdata7', 'userdata8', 'userdata9', 'cash', 'aonline', 'down', 'passive', 'disabledetailstat');

        foreach ($options as $type => $value) {

            if (in_array($type, $setuser) && $value !== false) {

                $true = 1;

                switch ($type) {

                    case 'tariff' :
                        $t = 1;
                        $val = (trim($_POST ['tariff_type']) == 'delayed') ? 'delayed' : 'now';

                        break;

                    case 'cash' :

                        $val = trim($_POST ['cash_type']) == 'add' ? 'add' : 'set';

                        break;

                    case (preg_match('#name|phone|note|address|email|userdata\d#i', $type) ? $type : !$type) :

                        $value = $this->encode12($this->utf_to_koi($value));

                        $val = 'value';

                        break;

                    default :

                        $val = 'value';

                        break;
                }

                $string .= "<$type $val=\"$value\" />";
            }
        }

        $string .= "</SetUser>";



        if ($true) {

            // sleep(1); // В базу відразу не записує СТГ, жде якусь секунду, а ми бачимо старі дані. Тож чекаєм секундочку, не вмрем :)


            if ($t == 1) {
                $this->sgconf("<SetUser><login value=\"$user\"/><down value=\"1\" /></SetUser>");
            }
            $this->sgconf($string);
            if ($t == 1) {
                $this->sgconf("<SetUser><login value=\"$user\"/><down value=\"0\" /></SetUser>");
            }
        } else {

            return false;
        }
    }

    function AddUser($user) {

        $string = "<AddUser><login value=\"$user\"/></AddUser>";

        return $this->sgconf($string);
    }

    function DelUser($user) {

        $string = "<DelUser login=\"$user\"/>";

        MySQL::Query('UPDATE  users SET `Deleted` = 1 where `login` = "' . $user . '"') or MySQL::Kill ();

        return $this->sgconf($string);
    }

    function SendMessage($user, $title, $message, $msgver = 1, $msgtype = 1, $repeat = 0, $repeatperiod = 0, $showtime = 0, $web = 0, $mail = 0, $auth = 0) {

        if ($web == 1) {
            $db = $this->dbconf();

            MySQL::Open($db ['name'], $db ['host'], $db ['user'], $db ['pass']) or MySQL::Error ();
            MySQL::Query('set names utf8') or MySQL::Kill ();
            MySQL::Query('insert into WebMessages(User,Date,Title,Message) values("' . $user . '",now(),"' . mysql_escape_string($title) . '","' . mysql_escape_string($message) . '")') or MySQL::Kill ();
        }
        if ($auth == 1) {

            $message = $this->encode12($this->utf_to_cp($message));
            $string = "<Message login=\"$user\" msgver=\"$msgver\" msgtype=\"$msgtype\" repeat=\"$repeat\" repeatperiod=\"$repeatperiod\" showtime=\"$showtime\" text=\"$message\" />";

            return $this->sgconf($string);
        }

        if ($mail == 1) {
            require_once 'mailer/class.phpmailer.php';

            $mail = new PHPMailer(true);
            $mail->IsSMTP();
            try {
                $mail->SMTPAuth = true;
                $mail->Host = "10.10.10.11";
                $mail->Port = 25;
                $mail->Username = "support@hatanet.com.ua";
                $mail->SMTPSecure = "tls";
                $mail->CharSet = "UTF-8";
                $mail->Password = "[fnfytn01081986";
                $mail->AddReplyTo('support@hatanet.com.ua', 'Підтримка ХатаНет');
                $mail->AddAddress($user . '@hatanet.com.ua', 'John Doe');
                $mail->SetFrom('support@hatanet.com.ua', 'Підтримка ХатаНет');
                $mail->AddReplyTo('support@hatanet.com.ua', 'Підтримка ХатаНет');
                $mail->Subject = 'Повідомлення від ХатаНет';
                $mail->MsgHTML($message);
                // $mail->AddAttachment('images/phpmailer.gif');      // attachment
                // $mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
                $mail->Send();
                //  echo "Message Sent OK</p>\n";
            } catch (phpmailerException $e) {
                //  echo $e->errorMessage(); //Pretty error messages from PHPMailer
            } catch (Exception $e) {
                //  echo $e->getMessage(); //Boring error messages from anything else!
            }
        }
    }

    function showTariff($tariff) {



        $query = $this->db->query("SELECT * FROM tariffs where name = '" . $tariff . "'");

        $results = $query->result_array();

        for ($j = 0; $j <= 9; $j++) {

            $arrTime = explode('-', $results ["Time$j"]);
            $day = explode(':', $arrTime [0]);
            $night = explode(':', $arrTime [1]);

            $results ['Time'] [$j] ['Dmin'] = $day [1];
            $results ['Time'] [$j] ['Dhour'] = $day [0];
            $results ['Time'] [$j] ['Nmin'] = $night [1];
            $results ['Time'] [$j] ['Nhour'] = $night [0];

            $results ['Threshold'] [$j] = $results ["Threshold$j"];

            $results ['PriceDayA'] [$j] = $results ["PriceDayA$j"];
            $results ['PriceDayB'] [$j] = $results ["PriceDayB$j"];
            $results ['PriceNightA'] [$j] = $results ["PriceNightA$j"];
            $results ['PriceNightB'] [$j] = $results ["PriceNightB$j"];
            $results ['NoDiscount'] [$j] = $results ["NoDiscount$j"];
            $results ['SinglePrice'] [$j] = $results ["SinglePrice$j"];
        }

        $info = $this->session->userdata('info'); //це тут <GetServerInfo/>

        preg_match_all('#<dir_name_([0-9])>(.*)</dir_name_[0-9]>#Uis', $xml, $names);

        for ($i = 0; $i < count($names [0]); $i++) {

            if ($names [2] [$i]) {
                $results ['dir'] [$i] ['num'] = $names [1] [$i];
                $results ['dir'] [$i] ['name'] = $this->koi_to_utf($this->decode12($names [2] [$i]));
            }
        }

        return $results;
    }

    function DelTariff($tariff) {

        return $this->sgconf("<DelTariff name=\"$tariff\"/>");
    }

    function AddTariff($tariff) {
        return $this->sgconf("<AddTariff name=\"$tariff\"/>");
    }

    function setTariff($tariff) {

        $options = $_POST ['options'];
        $dhour = $options ['dhour'];
        $dmin = $options ['dmin'];
        $nhour = $options ['nhour'];
        $nmin = $options ['nmin'];
        $PriceDay = $options ['PriceDay'];
        $PriceNight = $options ['PriceNight'];
        $Fee = $options ['Fee'];
        $Free = $options ['Free'];
        $PassiveCost = $options ['PassiveCost'];
        $TraffType = $options ['TraffType'];

        $tariff_arr = $this->showTariff($tariff);

        $string = "<SetTariff name=\"$tariff\">";
        $string .= "<Fee value=\"$Fee\"/>";
        $string .= "<Free value=\"$Free\"/>";
        $string .= "<PassiveCost value=\"$PassiveCost\"/>";
        $string .= "<TraffType value=\"$TraffType\"/>";

        foreach ($tariff_arr ['dir'] as $key => $value) {

            $string .= "<Time$key value=\"$dhour[$key]:$dmin[$key]-$nhour[$key]:$nmin[$key]\"/>";
        }

        foreach ($options ['PriceDay'] as $key => $value) {

            $arr = explode('/', $value);

            if ($arr [0] && $arr [1]) {
                $PriceDayAa = $arr [0];
                $PriceDayBb = $arr [1];
            } else {
                $PriceDayAa = $value;
                $PriceDayBb = $value;
            }

            $PriceDayAc [$key] = $PriceDayAa;
            $PriceDayBc [$key] = $PriceDayBb;
        }
        if (isset($options ['PriceNight'])) {
            foreach ($options ['PriceNight'] as $key => $value) {

                $arr = explode('/', $value);

                if ($arr [0] && $arr [1]) {
                    $PriceNightAa = $arr [0];
                    $PriceNightBb = $arr [1];
                } else {
                    $PriceNightAa = $value;
                    $PriceNightBb = $value;
                }

                $PriceNightAc [$key] = $PriceNightAa;
                $PriceNightBc [$key] = $PriceNightBb;
            }
        }
        for ($i = 0; $i <= 9; $i++) {

            if ($PriceDayAc [$i]) {

                if (isset($PriceDayA))
                    $sep = '/';
                $PriceDayA .= $sep . $PriceDayAc [$i];
            } else {
                if (isset($PriceDayA))
                    $sep = '/';
                $PriceDayA .= $sep . '0';
            }

            if ($PriceDayBc [$i]) {

                if (isset($PriceDayB))
                    $sep1 = '/';
                $PriceDayB .= $sep1 . $PriceDayBc [$i];
            } else {
                if (isset($PriceDayB))
                    $sep1 = '/';
                $PriceDayB .= $sep1 . '0';
            }

            if ($PriceNightAc [$i]) {

                if (isset($PriceNightA))
                    $sep2 = '/';
                $PriceNightA .= $sep2 . $PriceNightAc [$i];
            } else {
                if (isset($PriceNightA))
                    $sep2 = '/';
                $PriceNightA .= $sep . '0';
            }

            if ($PriceNightBc [$i]) {

                if (isset($PriceNightB))
                    $sep3 = '/';
                $PriceNightB .= $sep3 . $PriceNightBc [$i];
            } else {
                if (isset($PriceNightB))
                    $sep3 = '/';
                $PriceNightB .= $sep3 . '0';
            }

            ///////////////////////////////////////


            if ($options ['Threshold'] [$i]) {

                if (isset($Threshold))
                    $sep4 = '/';
                $Threshold .= $sep4 . $options ['Threshold'] [$i];
            } else {

                if (isset($Threshold))
                    $sep4 = '/';
                $Threshold .= $sep4 . '0';
            }

            ////////////////////////////////////////


            if ($options ['SinglePrice'] [$i]) {

                if (isset($SinglePrice))
                    $sep5 = '/';

                $SinglePrice .= $sep5 . $options ['SinglePrice'] [$i];
            } else {

                if (isset($SinglePrice))
                    $sep5 = '/';

                $SinglePrice .= $sep5 . "0";
            }

            ////////////////////////////////////////


            if ($options ['NoDiscount'] [$i] != false) {

                if (isset($NoDiscount))
                    $sep6 = '/';
                $NoDiscount .= $sep6 . $options ['NoDiscount'] [$i];
            } else {

                if (isset($NoDiscount))
                    $sep6 = '/';
                $NoDiscount .= $sep6 . '0';
            }
        }

        $string .= "<PriceDayA value=\"$PriceDayA\"/>";
        $string .= "<PriceDayB value=\"$PriceDayB\"/>";
        $string .= "<PriceNightA value=\"$PriceNightA\"/>";
        $string .= "<PriceNightB value=\"$PriceNightB\"/>";
        $string .= "<SinglePrice value=\"$SinglePrice\"/>";
        $string .= "<NoDiscount value=\"$NoDiscount\"/>";
        $string .= "<Threshold value=\"$Threshold\"/>";
        $string .= "</SetTariff>";

        return $this->sgconf($string);
    }

    function editStreet() {

        $street = trim($_POST ['street']);
        $street1 = trim($_GET ['street']);
        $id = trim($_GET ['id']);
        $db = $this->dbconf();

        MySQL::Open($db ['name'], $db ['host'], $db ['user'], $db ['pass']) or MySQL::Error ();
        MySQL::Query('set names utf8') or MySQL::Kill ();
        if ($_GET ['delete'] == 1 && isset($id)) {

            MySQL::Query('delete from Streets where ID= ' . mysql_escape_string($id) . '') or MySQL::Kill ();
        }

        if ($_GET ['update'] == 1 && isset($id)) {

            MySQL::Query('update  Streets set Name="' . mysql_escape_string($street1) . '" where  ID= ' . mysql_escape_string($id) . '') or MySQL::Kill ();
        }

        switch ($_POST ['true']) {
            case '4' :
                if ($street) {
                    MySQL::Query('insert into Streets(Name) values ("' . mysql_escape_string($street) . '")') or MySQL::Kill ();
                }

                break;
        }
    }

    function actionAdmins($type) {

        $db = $this->dbconf();

        MySQL::Open($db ['name'], $db ['host'], $db ['user'], $db ['pass']) or MySQL::Error ();

        if ($_POST ['add'] == 1 or $_POST ['edit'] == 1 or $_POST ['del'] == 1) {

            $adminc = $_POST ['admin'];

            if ($adminc ["ChgTariff"] == "1") {
                $priv .= "10";
            } else {
                $priv .= "00";
            }
            if ($adminc ["ChgAdmin"] == "1") {
                $priv .= "10";
            } else {
                $priv .= "00";
            }
            if ($adminc ["UsrAddDel"] == "1") {
                $priv .= "10";
            } else {
                $priv .= "00";
            }
            if ($adminc ["ChgPassword"] == "1") {
                $priv .= "10";
            } else {
                $priv .= "00";
            }
            if ($adminc ["ChgCash"] == "1") {
                $priv .= "10";
            } else {
                $priv .= "00";
            }
            if ($adminc ["ChgConf"] == "1") {
                $priv .= "10";
            } else {
                $priv .= "00";
            }
            if ($adminc ["ChgStat"] == "1") {
                $priv .= "1";
            } else {
                $priv .= "0";
            }

            $priv = bindec($priv);




            if ($_POST ['edit'] == 1) {
                if (trim($_POST ['password']) != '') {
                    $passedit = 'password="' . $_POST ['password'] . '"';
                }

                $this->sgconf('<ChgAdmin login="' . $_POST ['login'] . '" priv="' . $priv . '" ' . $passedit . ' />');
            }

            if ($_POST ['add'] == 1) {

                $this->sgconf('<AddAdmin login="' . $_POST ['login'] . '"/>');
                $this->sgconf('<ChgAdmin login="' . $_POST ['login'] . '" priv="' . $priv . '" password="' . $_POST ['password'] . '"/>');
            }
            if ($_POST ['del'] == 1) {
                $this->sgconf('<DelAdmin login="' . $_POST ['login'] . '"/>');
            }
        }



        switch ($type) {
            case 'list':
                MySQL::Query('select login from admins') or MySQL::Kill ();

                $xml = $this->sgconf('<Getadmins/>');
                //print 111;
                preg_match_all('#<admin login="([^>]+)">(.*)</admin>#Uis', $xml, $admins);

                $i = 0;
                while (!MySQL::EndOfSeek ()) {
                    preg_match('#<login>(.*)</login>#Uis', $admins ['0'] [$i], $login);
                    //preg_match ( '#<priv>(.*)</priv>#Uis', $admins ['0'] [$i], $priv );

                    $admin [$i] ['login'] = $login [1];
                    //$admin [$i] ['priv'] = $priv [1];
                    $admin [$i] = MySQL::RowArray ();
                    ++$i;
                }

                return $admin;

                break;

            case 'edit':

                MySQL::Query('select * from admins where login = "' . $_GET['admin'] . '"') or MySQL::Kill ();

                return MySQL::RowArray ();

                break;

            default:
                ;
                break;
        }
    }

    function sgconf($attr) {

        $query = $this->db->query('select password from admins where login = "' . $this->session->userdata('login') . '"');
        $res = $query->row();

        $cmd = $this->config->item('sgconf_xml') . ' -s ' . $this->config->item('stg_host') . ' -p ' . $this->config->item('stg_port') . ' -a ' . $this->session->userdata('login') . ' -w [fnfytn01081986 -r \'' . $attr . '\'';

       // file_put_contents('/home/morfey/3333', $cmd);
        if (function_exists('shell_exec')) {

            $result = shell_exec($cmd);
        } elseif (function_exists('passthru')) {

            passthru($cmd, $result);
        } else {

            $handle = popen($cmd, "r");

            $result = fread($handle, 128);

            pclose($handle);
        }

        switch (function_exists('shell_exec')) {
            case $value:


                break;

            default:
                break;
        }


        return trim($result);
    }

    function decode12($src) {
        $ofs = ord('a');
        $dst = "";
        for ($i = 0; $i < (strlen($src) / 2); $i++) {
            $c1 = (ord($src [$i * 2]) - $ofs);
            $c2 = (ord($src [$i * 2 + 1]) - $ofs) << 4;
            $dst .= chr($c1 + $c2);
        }
        return $dst;
    }

    function encode12($src) {
        $len = strlen($src);
        $ofs = ord('a');
        $dst = "";
        for ($i = 0; $i <= $len; $i++) {
            $c1 = (ord($src [$i]) & 15) + $ofs;
            $c2 = (ord($src [$i]) >> 4) + $ofs;
            $dst .= chr($c1) . chr($c2);
        }
        return $dst;
    }

    function ShowTariffs() {
        $query = $this->db->query('SELECT name,Fee FROM tariffs order BY name ASC');

        return $query->result_array();
    }

    function ShowStreets() {
        $this->db->query('set names utf8');
        $query = $this->db->query('SELECT * FROM Streets order BY Name ASC ');
        return $query->result_array();
    }

    function traff() {
        global $srv;
        $db = $this->dbconf();

        MySQL::Open($db ['name'], $db ['host'], $db ['user'], $db ['pass']) or MySQL::Error ();

        MySQL::Query('select distinct (month) as month  from stat where year="' . date('Y') . '" order by month ASC') or MySQL::Kill ();

        $i = 0;
        while (!MySQL::EndOfSeek ()) {

            $result[$i] = MySQL::RowArray ();
            //$result [$i]['D0']
            ++$i;
        }
//print_r($result);
        $count = count($result);
        $xml = $_SESSION ['info'];
        //print_r($xml);
        preg_match_all('#<dir_name_([0-9])>(.*)</dir_name_[0-9]>#Uis', $xml, $names);
        //2i - name; 1i num


        for ($i = 0; $i < count($names [0]); $i++) {

            if ($names [2] [$i]) {





                //&gt;
                $result ['dir'] [$i] ['num'] = $names [1] [$i];
                $result ['dir'] [$i] ['name'] = ($srv ['stgver'] == '1') ? USER::koi_to_utf($names [2] [$i]) : USER::koi_to_utf(USER::decode12($names [2] [$i]));
                $k = 0;
                while ($k < $count) {

                    MySQL::Query('select SUM(D' . $names [1] [$i] . ') as dsum, SUM(U' . $names [1] [$i] . ') as usum from stat where month="' . ($result[$k]['month']) . '" and year="' . date('Y') . '" order by month ASC') or MySQL::Kill ();
                    $sums = MySQL::RowArray ();
                    //echo $i;
                    $result ['dir'] [$i] ['Dtype'] [$result [$k] ['month']] = $sums['dsum'];
                    $result ['dir'] [$i] ['Utype'] [$result [$k] ['month']] = $sums['usum'];
                    ++$k;
                }
            }
        }
        //		print_r($result ['dir']);
        //		print_r($result);


        return $result;
    }

    function Size2Str2($size) {
        $kb = 1024;
        $mb = 1024 * $kb;
        $gb = 1024 * $mb;
        $tb = 1024 * $gb;

        if ($size < $kb) {
            return $size . ' байт';
        } else if ($size < $mb) {
            return round($size / $kb, 2) . ' Кб';
        } else if ($size < $gb) {
            return round($size / $mb, 2);
        } else if ($size < $tb) {
            return round($size / $gb, 2) . ' Гб';
        } else {
            return round($size / $tb, 2) . ' Тб';
        }
    }

    function showInfo() {

        $query1 = $this->db->query('select count(1) as count from users where IsOnline = 1');
        $info->allOnline = $query1->row();

        $query2 = $this->db->query('select count(1) as count from users where AlwaysOnline = 1');
        $info->AlwaysOnline = $query2->row();

        $query3 = $this->db->query('select count(1) as count from users where Down = 1');
        $info->Down = $query3->row();

        $query4 = $this->db->query('select count(1) as count from users where Passive = 1');
        $info->Passive = $query4->row();

        $query5 = $this->db->query('select count(1) as count from users where Cash < 0');
        $info->fucker = $query5->row();

        $query6 = $this->db->query('select SUM(D0)+SUM(D1)+SUM(D2)+SUM(D3)+SUM(D4)+SUM(D5)+SUM(D6)+SUM(D7)+SUM(D8)+SUM(D9) as count from stat where month="' . ltrim(date('m', strtotime('-2 month')), "0") . '"');
        $info->AllDown = $query6->row();

        $query7 = $this->db->query('select SUM(U0)+SUM(U1)+SUM(U2)+SUM(U3)+SUM(U4)+SUM(U5)+SUM(U0)+SUM(U7)+SUM(U8)+SUM(U9) as count from stat where month="' . ltrim(date('m', strtotime('-2 month')), "0") . '"');
        $info->AllUp = $query7->row();

        $query8 = $this->db->query('select SUM(D0)+SUM(D1)+SUM(D2)+SUM(D3)+SUM(D4)+SUM(D5)+SUM(D6)+SUM(D7)+SUM(D8)+SUM(D9) as count from stat where month="' . ltrim(date('m', strtotime('-1 month')), "0") . '"');
        $info->AllDown2 = $query8->row();

        $query9 = $this->db->query('select SUM(U0)+SUM(U1)+SUM(U2)+SUM(U3)+SUM(U4)+SUM(U5)+SUM(U0)+SUM(U7)+SUM(U8)+SUM(U9) as count from stat where month="' . ltrim(date('m', strtotime('-1 month')), "0") . '"');
        $info->AllUp2 = $query9->row();

        $query10 = $this->db->query('SELECT users.*, s.Name as StreetName, t.Fee as Fee FROM users LEFT JOIN Streets as s ON s.ID=users.StreetID LEFT JOIN tariffs as t ON users.Tariff = t.name order by Created DESC limit 5');
        $info->lastusers = $query10->result();


        $month = array('01' => 'Січень', '02' => 'Лютий', '03' => 'Березень', '04' => 'Квітень', '05' => 'Травень', '06' => 'Червень', '07' => 'Липень', '08' => 'Серпень', '09' => 'Вересень', '10' => 'Жовтень', '11' => 'Листопад', '12' => 'Грудень');

        $info->server = simplexml_load_string($this->session->userdata('info'));


        return $info;
    }

    function showUsers($per_page, $start, &$count_all) {



        if ($_POST ['filter'] == 1) {

            if (is_numeric($_POST ['streetid'])) {
                $streetid = "and StreetID = '" . trim($_POST ['streetid']) . "'";
            }

            if ($_POST ['Apartn']) {
                $Apartn = "and Apartn = " . trim($_POST ['Apartn']);
            }

            if ($_POST ['Buildingn']) {
                $Buildingn = "and Buildingn = '" . trim($_POST ['Buildingn']) . "'";
                //print $Buildingn;
            }

            if ($_POST ['Entrance']) {
                $Entrance = "and Entrance = " . trim($_POST ['Entrance']);
            }

            if ($_POST ['Floor']) {
                $Floor = "and Floor = " . trim($_POST ['Floor']);
            }

            if ($_POST ['tariff']) {
                $tariff = "and Tariff = '" . trim($_POST ['tariff']) . "'";
            }

            if ($_POST ['balance'] && is_numeric($_POST ['balance'])) {

                if ($_POST ['balanceval'] == 1) {
                    $sep = "<";
                }
                if ($_POST ['balanceval'] == 2) {
                    $sep = ">";
                }

                if ($_POST ['balanceval'] == 3) {
                    $sep = "=";
                }

                $tariff = "and Cash " . $sep . " '" . trim($_POST ['balance']) . "'";
            }


            if (preg_match('#[0-9]{4}-[0-9]{2}-[0-9]{2}#Uis', $_POST ['from']) && preg_match('#[0-9]{4}-[0-9]{2}-[0-9]{2}#Uis', $_POST ['to'])) {

                $date = "and Created >= '" . trim($_POST ['from']) . "' and Created <= '" . trim($_POST ['to']) . "'";
            }

            if ($_POST ['on'] == 1) {

                $on = "and IsOnline = '1'";
            }
        }


        switch ($_COOKIE['sort']) {
            case "login":
                $order = 'login';
                break;
            case "nd":
                $order = 'Userdata2';
                $null = '+0';
                break;
            case "ip":
                $order = 'inet_aton(users.IP)';
                break;
            case "tariff":
                $order = 'Tariff';
                break;
            case "name":
                $order = 'RealName';
                break;
            case "upload":
                $order = 'U0';
                break;
            case "download":
                $order = 'D0';
                break;
            case "cash":
                $order = 'cash';
                break;
            default:
                $order = 'login';
                break;
        }

        switch ($_COOKIE['order']) {
            case "1":
                $by = "ASC";
                break;
            case "2":
                $by = "DESC";
                break;

            default:
                $by = "ASC";
                break;
        }

        $this->db->query('set names cp1251');
        $query = $this->db->query('SELECT users.*,s.ID as sID, s.Name as StreetName FROM users LEFT JOIN Streets as s ON s.ID = users.StreetID  where Deleted !=1 ' . $streetid . ' ' . $Floor . ' ' . $Apartn . ' ' . $Entrance . '  ' . $Buildingn . ' ' . $tariff . ' ' . $date . ' ' . $on . '  order by ' . $order . '' . $null . ' ' . $by . ' limit ' . $start . ',' . $per_page);


        $i = 0;


        foreach ($query->result_array() as $user) {
            $users [$i] = $user;
            $users [$i] ['RealName'] = $this->koi_to_utf($user ['RealName']);
            $users [$i] ['Address'] = $this->koi_to_utf($user ['Address']);
            $users [$i] ['StreetName'] = $this->cp_to_utf($user ['StreetName']);
            if ($users [$i] ['IsOnline'] == 1) {
                $users [$i] ['Status'] = 1;
            } else {
                $users [$i] ['Status'] = 0;
            }
            $users [$i] ['Upload'] = $this->Size2Str($user ['U0']);
            $users [$i] ['Download'] = $this->Size2Str($user['D0']);
            $users [$i] ['Cash'] = round($user ['Cash'], 2);


            ++$i;
        }

        $query = $this->db->query('SELECT count(1) as count FROM users where Deleted !=1 ' . $streetid . ' ' . $Floor . ' ' . $Apartn . ' ' . $Entrance . '  ' . $Buildingn . ' ' . $tariff . ' ' . $date . ' ' . $on . ' ');

        $row = $query->row();

        $count_all = $row->count;

        return $users;
    }

    function showUser($option) {


        //$db = $this->dbconf();
        //MySQL::Open($db ['name'], $db ['host'], $db ['user'], $db ['pass']) or MySQL::Error ();
        $query = $this->db->query('set names cp1251');
        $query = $this->db->query('SELECT users.*, s.Name as StreetName, t.Fee as Fee FROM users LEFT JOIN Streets as s ON s.ID=users.StreetID LEFT JOIN tariffs as t ON users.Tariff = t.name where `login` = "' . $option . '"');
        //MySQL::Query('SELECT users.*, s.Name as StreetName, t.Fee as Fee FROM users LEFT JOIN Streets as s ON s.ID=users.StreetID LEFT JOIN tariffs as t ON users.Tariff = t.name where `login` = "' . $option . '"') or MySQL::Kill ();

        $user = $query->row();

        $user->RealName = $this->koi_to_utf($user->RealName);
        $user->Address = $this->koi_to_utf($user->Address);
        $user->StreetName = $this->cp_to_utf($user->StreetName);
        $user->Note = $this->koi_to_utf($user->Note);
        $user->Upload = $this->Size2Str($user->U0);
        $user->Download = $this->Size2Str($user->D0);




        if ($user->IsOnline == 1) {
            $user->Status = 1;
        } else {
            $user->Status = 0;
        }
        $user->Cash = round($user->Cash, 2);
        $user->LastCashAddTime = date("m.d.Y H:i:s", $user->LastCashAddTime);

        //  $user['freez'] = $this->freezing('show', $option, false, false);


        return $user;
    }

    function koi_to_utf($key) {
        return iconv('KOI8-U', 'UTF-8', $key);
    }

    function utf_to_koi($key) {
        return iconv('UTF-8', 'KOI8-U', $key);
    }

    function autocomplete($type, $key) {

        $key = $this->utf_to_koi($key);

        switch ($type) {

            case 'login' :

                $table = "login";

                break;

            case 'ip' :

                $table = "IP";

                break;

            case 'name' :

                $table = "RealName";

                break;
        }
        //   $db = $this->dbconf();

        $this->db->query('set names cp1251');
        $query = $this->db->query('SELECT  s.Name as StreetName,u.* FROM users as u LEFT JOIN Streets as s ON s.ID=u.StreetID where `' . $table . '` like "%' . $key . '%" and Deleted != 1 order by u.login ASC limit 5');

        //    MySQL::Query() or MySQL::Kill ();
        $i = 0;
        foreach ($query->result_array() as $users) {

            $user [$i] = $users;
            $user [$i] ['uselogin'] = preg_replace("#$key#Uis", "<span class='red'>$key</span>", $this->koi_to_utf($users ['login']));
            $user [$i] ['IP'] = preg_replace("#$key#Uis", "<span class='red'>$key</span>", $this->koi_to_utf($users ['IP']));
            $user [$i] ['RealName'] = preg_replace("#" . $this->koi_to_utf($key) . "#uUis", "<span class='red'>" . $this->koi_to_utf($key) . "</span>", htmlspecialchars($this->koi_to_utf($users ['RealName'])));
            //print $this->koi_to_utf($key);
            $user [$i] ['StreetName'] = $this->cp_to_utf($users ['StreetName']);



            ++$i;
        }


        return $user;
    }

    function CreateUser($option) {

        $db = $this->dbconf();

        MySQL::Open($db ['name'], $db ['host'], $db ['user'], $db ['pass']) or MySQL::Error ();

        $options = $this->info('options', false);

        $address = $this->info('address', false);

        STG::AddUser($option);

        STG::setVal($options, $option); // Передаємо функції масив з даними


        foreach ($address as $type => $value) {

            if ($value !== false) { //Міняєм адресу користувача, якщо є зміни
                MySQL::Query('update  users set `' . $type . '` = "' . $value . '" where login="' . $option . '"  limit 1') or MySQL::Kill ();
            }
        }

        MySQL::Query('update users set Created=NOW()  where `login` = "' . $option . '"  limit 1') or MySQL::Kill ();

        MySQL::Query('Select MAX(Userdata2*1) as `max` from `users`') or MySQL::Kill ();

        $dres = MySQL::RowArray ();

        $dID = $dres ['max'] + 1;

        unset($options);

        $options ['userdata2'] = $dID; // Да, хуйня, але тимчасове рішення :)


        STG::setVal($options, $option);




        $timestart = time ();

        while (1) {

            MySQL::Query('select count(1) as c from `users`  where `login` = "' . $option . '"') or MySQL::Kill ();

            $user = MySQL::RowArray ();

            if ($user ['c'] == 0) {

                $time = time ();

                if (($time - $timestart) >= 120) {

                    break;
                } else {

                    sleep(2);
                }
            } else {

                break;
            }
        }
    }

    function info($type, $user) {

        if ($type == 'address') {

            $address ['StreetID'] = (trim($_POST ['StreetID']) == trim($user->StreetID)) || (!$_POST ['StreetID']) ? false : trim($_POST ['StreetID']);
            $address ['Buildingn'] = (trim($_POST ['Buildingn']) == trim($user->Buildingn)) || (!$_POST ['Buildingn']) ? false : trim($_POST ['Buildingn']);
            $address ['Entrance'] = (trim($_POST ['Entrance']) == trim($user->Entrance)) || (!$_POST ['Entrance']) ? false : trim($_POST ['Entrance']);
            $address ['Floor'] = (trim($_POST ['Floor']) == trim($user->Floor)) || (!$_POST ['Floor']) ? false : trim($_POST ['Floor']);
            $address ['Apartn'] = (trim($_POST ['Apartn']) == trim($user->Apartn)) || (!$_POST ['Apartn']) ? false : trim($_POST ['Apartn']);

            return $address;
        } elseif ($type == 'options') {

            $options ['down'] = (!$_POST ['options'] ['down'] && $user->Down == 1 && $_POST ['type'] == 1) ? 0 : (!$_POST ['options'] ['down'] && $user->Down == 0 ? false : ($_POST ['options'] ['down'] && $user->Down == 1 ? false : 1));
            $options ['passive'] = (!$_POST ['options'] ['passive'] && $user->Passive == 1 && $_POST ['type'] == 1) ? 0 : (!$_POST ['options'] ['passive'] && $user->Passive == 0 ? false : ($_POST ['options'] ['passive'] && $user->Passive == 1 ? false : 1));
            $options ['aonline'] = (!$_POST ['options'] ['aonline'] && $user->AlwaysOnline == 1 && $_POST ['type'] == 1) ? 0 : (!$_POST ['options'] ['aonline'] && $user->AlwaysOnline == 0 ? false : ($_POST ['options'] ['aonline'] && $user->AlwaysOnline == 1 ? false : 1));
            $options ['disabledetailstat'] = (!$_POST ['options'] ['disabledetailstat'] && $user->DisabledDetailStat == 1 && $_POST ['type'] == 1) ? 0 : (!$_POST ['options'] ['disabledetailstat'] && $user->DisabledDetailStat == 0 ? false : ($_POST ['options'] ['disabledetailstat'] && $user->DisabledDetailStat == 1 ? false : 1));

            //$options ['disabledetailstat'] = (! $_POST ['options'] ['disabledetailstat'] && $user ['DisabledDetailStat'] == 1 && $_POST['type'] == 1 ) ? 0 :  (! $_POST ['options'] ['disabledetailstat'] && $user ['DisabledDetailStat'] == 1  ? false : 1 );

            $options ['message'] = trim($_POST ['message']);
            $options ['name'] = (trim($_POST ['options'] ['name']) == trim($this->koi_to_utf($user->RealName))) || (!$_POST ['options'] ['name']) ? false : trim($_POST ['options'] ['name']);
            $options ['ip'] = (trim($_POST ['options'] ['ip']) == trim($user->IP)) || (!$_POST ['options'] ['ip']) ? false : trim($_POST ['options'] ['ip']);
            $options ['tariff'] = (trim($_POST ['options'] ['tariff']) == trim($user->Tariff)) ? false : (!$_POST ['options'] ['tariff'] ? false : trim($_POST ['options'] ['tariff']));
            $options ['cash'] = (!isset($_POST ['options'] ['cash'])) ? false : trim($_POST ['options'] ['cash']);
            $options ['phone'] = ((trim($_POST ['options'] ['phone']) == trim($user->Phone)) || (!isset($_POST ['options'] ['phone']))) ? false : trim($_POST ['options'] ['phone']);
            $options ['note'] = ((trim($_POST ['options'] ['note']) == trim($this->koi_to_utf($user->Note))) || (!isset($_POST ['options'] ['note']))) ? false : trim($_POST ['options'] ['note']);
            $options ['email'] = (trim($_POST ['options'] ['email']) == trim($user->Email)) || (!isset($_POST ['options'] ['email'])) ? false : trim($_POST ['options'] ['email']);
            $options ['userdata0'] = (trim($_POST ['options'] ['userdata0']) == trim($user->Userdata0)) || (!isset($_POST ['options'] ['userdata0'])) ? false : trim($_POST ['options'] ['userdata0']);
            $options ['userdata1'] = (trim($_POST ['options'] ['userdata1']) == trim($user->Userdata1)) || (!isset($_POST ['options'] ['userdata1'])) ? false : trim($_POST ['options'] ['userdata1']);
            $options ['userdata2'] = (trim($_POST ['options'] ['userdata2']) == trim($user->Userdata2)) || (!isset($_POST ['options'] ['userdata2'])) ? false : trim($_POST ['options'] ['userdata2']);
            $options ['password'] = (trim($_POST ['options'] ['password']) == trim($user->Password)) || (trim($_POST ['options'] ['password']) == '') ? false : trim($_POST ['options'] ['password']);


            return $options;
        }
    }

    function userEdit($option) {
        $this->db->query('set names cp1251');
        $query = $this->db->query('SELECT * FROM users where `login` = "' . $option . '"  limit 1');

        $user = $query->row();

//file_put_contents('/home/morfey/33333', $user->IP);

        $options = $this->info('options', $user);

        $address = $this->info('address', $user);
//print_r($options);
        //if (preg_match('#[0-9]{4}-[0-9]{2}-[0-9]{2}#Uis', $_POST ['from']) && preg_match('#[0-9]{4}-[0-9]{2}-[0-9]{2}#Uis', $_POST ['to'])) {
        //  $this->freezing('set', $option, trim($_POST ['from']), trim($_POST ['to']));
        //}

        if ($_POST['paytype'] == 'bank' || $_POST['paytype'] == 'nal') {
            $this->db->query('set names utf8');
            $this->db->query('insert into pays.Cash (User,Date,Cash,Paytype,Note,Status,Note2,Cash2) values("' . $option . '",NOW(),"' . $options['cash'] . '","' . $_POST['paytype'] . '","Поповнення через веб морду",1,"Поповнення через веб морду","' . $options['cash'] . '")');
        }


        $this->setVal($options, $option); // Передаємо функції масив з даними

        if( $_POST['options']['created'] != '' && preg_match('#[0-9]{4}-[0-9]{2}-[0-9]{2}|[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}#Uis', $_POST['options']['created']) && ($user->Created != $_POST['options']['created'] )){

            file_put_contents('/home/morfey/33333', $_POST['options']['created']);
            
            $this->db->query('update  users set Created =  "' . $_POST['options']['created'] . '" where login="' . $option . '"');
        }


        foreach ($address as $type => $value) {

            if ($value !== false) { //Міняєм адресу користувача, якщо є зміни
                $this->db->query('update  users set `' . $type . '` = "' . $value . '" where login="' . $option . '"  limit 1');
            }
        }

        if ($_POST ['mess'] == 1) {

        }
    }

    function Size2Str($size) {
        $kb = 1024;
        $mb = 1024 * $kb;
        $gb = 1024 * $mb;
        $tb = 1024 * $gb;
        if ($size < $kb) {
            return '<span class="b">' . $size . ' байт</span>';
        } else if ($size < $mb) {
            return '<span class="kb">' . round($size / $kb, 2) . ' Кб</span>';
        } else if ($size < $gb) {
            return '<span class="mb">' . round($size / $mb, 2) . ' Мб</span>';
        } else if ($size < $tb) {
            return '<span class="gb">' . round($size / $gb, 2) . ' Гб</span>';
        } else {
            return '<span class="tb">' . round($size / $tb, 2) . ' Тб</span>';
        }
    }

    function semantic($i, &$words, &$fem, $f) {

        global $tarrifs;
        global $months;
        global $_1_2, $_1_19, $des, $hang, $namerub, $nametho;
        global $_1_2, $_1_19, $des, $hang, $namerub, $nametho, $kopeek;
        $_1_2 [1] = "одна ";
        $_1_2 [2] = "дві ";

        $_1_19 [1] = "один ";
        $_1_19 [2] = "два ";
        $_1_19 [3] = "три ";
        $_1_19 [4] = "чотири ";
        $_1_19 [5] = "п'ять ";
        $_1_19 [6] = "шість ";
        $_1_19 [7] = "сім ";
        $_1_19 [8] = "вісім ";
        $_1_19 [9] = "дев'ять ";
        $_1_19 [10] = "десять ";

        $_1_19 [11] = "одинадцять ";
        $_1_19 [12] = "дванадцять ";
        $_1_19 [13] = "тринадцять ";
        $_1_19 [14] = "чотирнадцять ";
        $_1_19 [15] = "п'ятнадцять ";
        $_1_19 [16] = "шістнадцять ";
        $_1_19 [17] = "сімнадцять ";
        $_1_19 [18] = "вісімнадцять ";
        $_1_19 [19] = "дев'ятнадцять ";

        $des [2] = "двадцять ";
        $des [3] = "тридцять ";
        $des [4] = "сорок ";
        $des [5] = "п'ятдесят ";
        $des [6] = "шістдесят ";
        $des [7] = "сімдесят ";
        $des [8] = "вісімдесят ";
        $des [9] = "дев'яносто ";

        $hang [1] = "сто ";
        $hang [2] = "двісті ";
        $hang [3] = "триста ";
        $hang [4] = "чотириста ";
        $hang [5] = "п'ятсот ";
        $hang [6] = "шістсот ";
        $hang [7] = "сімсот ";
        $hang [8] = "вісімсот ";
        $hang [9] = "дев'ятсот ";

        $namerub [1] = "гривня ";
        $namerub [2] = "гривні ";
        $namerub [3] = "гривень ";

        $nametho [1] = "тисяча ";
        $nametho [2] = "тисячі ";
        $nametho [3] = "тисяч ";


        $kopeek [1] = "копійка ";
        $kopeek [2] = "копійки ";
        $kopeek [3] = "копійок ";
        global $_1_2, $_1_19, $des, $hang, $namerub, $nametho;
        $words = "";
        $fl = 0;
        if ($i >= 100) {
            $jkl = intval($i / 100);
            $words .= $hang [$jkl];
            $i %= 100;
        }
        if ($i >= 20) {
            $jkl = intval($i / 10);
            $words .= $des [$jkl];
            $i %= 10;
            $fl = 1;
        }
        switch ($i) {
            case 1 :
                $fem = 1;
                break;
            case 2 :
            case 3 :
            case 4 :
                $fem = 2;
                break;
            default :
                $fem = 3;
                break;
        }
        if ($i) {
            if ($i < 3 && $f > 0) {
                if ($f >= 2) {
                    $words .= $_1_19 [$i];
                } else {
                    $words .= $_1_2 [$i];
                }
            } else {
                $words .= $_1_19 [$i];
            }
        }
    }

    function docprint() {
        global $srv;
        $months = array('01' => 'Січня', '02' => 'Лютого', '03' => 'Березня', '04' => 'Квітня', '05' => 'Травня', '06' => 'Червня', '07' => 'Липня', '08' => 'Серпня', '09' => 'Вересня', '10' => 'Жовтня', '11' => 'Листопада', '12' => 'Грудня');

        $summ = trim($_POST['summ']);
        $summp = trim($_POST['summp']);
        $save = trim($_POST['save']);
        $paytype = 'nal';

        foreach ($months as $key => $value) {
            if ($key == date('m')) {
                $month = $value;
            }
        }

        switch ($_POST['doctype']) {

            case '1':
                $file = file_get_contents($srv['patch'] . 'rtf/kvit.rtf');
                $name = "Квитанція";
                break;

            case '2':
                $file = file_get_contents($srv['patch'] . 'rtf/rah.rtf');
                $name = "Рахунок";
                break;

            case '3':
                $file = file_get_contents($srv['patch'] . 'rtf/kvit_rah.rtf');
                $name = "Квитанція+Рахунок";
                break;

            case '4':
                $file = file_get_contents($srv['patch'] . 'rtf/akt.rtf');
                $name = "Акт виконаних робіт";
                break;

            case '5':
                $file = file_get_contents($srv['patch'] . 'rtf/dog.rtf');
                $name = "Договір";
                break;

            case '6':
                $file = file_get_contents($srv['patch'] . 'rtf/dog2.rtf');
                $name = "Договір(2копії)";
                break;
        }

//$file = preg_replace('#zzzzzNUMBERzzzzz#Uis',$number,$file);//sdgfsgsdfgsdfg



        $file = preg_replace('#zzzzzDATAzzzzz#Uis', date('d.m.Y'), $file);
        if ($_POST ['pidkl'] == 1) {
            $suma = $_POST ['summ'] + $_POST ['summp'];
        } else {
            $suma = $_POST ['summ'];
        }
        $file = preg_replace('#zzzzzSUMAzzzzz#Uis', $suma . ",00", $file);
        $file = preg_replace('#zzzzzSUMA2zzzzz#Uis', $_POST ['tariff'] . ",00", $file);
        $file = preg_replace('#zzzzzUSERzzzzz#Uis', $this->utf_to_cp($_POST ['name']), $file);
        $file = preg_replace('#zzzzzPRIZzzzzz#Uis', $this->utf_to_cp($_POST ['comment']), $file);
        $file = preg_replace('#zzzzzPRIZ2zzzzz#Uis', $this->utf_to_cp($_POST ['tariffname']), $file);
        $file = preg_replace('#zzzzzNDOGzzzzz#Uis', $_POST ['ndog'], $file);

        if ($_POST ['pidkl'] == 1) {
            $sumas = $_POST ['summ'] + $_POST ['summp'];
        } else {
            $sumas = $_POST ['summ'];
        }
        $file = preg_replace('#zzzzzSUMASzzzzz#Uis', $this->utf_to_cp($this->num2str($sumas)), $file);
        $file = preg_replace('#zzzzzSUMAS2zzzzz#Uis', $this->utf_to_cp($this->num2str($_POST ['tariff'])), $file);
        $file = preg_replace('#zzzzzSTREETzzzzz#Uis', $this->utf_to_cp($_POST ['street']), $file);

        $file = preg_replace('#zzzzzTELzzzzz#Uis', $_POST ['tel'], $file);
        $file = preg_replace('#zzzzzLOGINzzzzz#Uis', $_POST ['login'], $file);
        $file = preg_replace('#zzzzzIPzzzzz#Uis', $_POST ['ip'], $file);
        $file = preg_replace('#zzzzzPASSzzzzz#Uis', $_POST ['password'], $file);
        $file = preg_replace('#zzzzzDATEzzzzz#Uis', date('d'), $file);
        $file = preg_replace('#zzzzzDATE2zzzzz#Uis', $this->utf_to_cp($month), $file);
        $file = preg_replace('#zzzzzDATE3zzzzz#Uis', date('Y'), $file);

        if ($_POST ['save'] == 1 && ($_POST ['doctype'] == 3 || $_POST ['doctype'] == 1 || $_POST ['doctype'] == 2 || $_POST ['doctype'] == 4)) {
            if ($_POST ['doctype'] == 3) {
                $_POST ['doctype'] = 1;
            }

            MySQL::Query('select max(Number) as max from pays.Payments where Type=' . $_POST ['doctype']) or MySQL::Kill ();

            $doctype_arr = MySQL::RowArray ();

            $number = $doctype_arr ['max'] + 1;
            MySQL::Query('set names utf8') or MySQL::Kill ();
            MySQL::Query('insert into pays.Payments(Number,Type,Paytype,Date,User,Cash,Note) values (' . $number . ',"' . $_POST ['doctype'] . '","nal",NOW(),"' . trim($_POST ['login']) . '","' . $suma . '","' . mysql_escape_string($_POST ['comment']) . '")') or MySQL::Kill ();

            $file = preg_replace('#zzzzzNUMBERzzzzz#Uis', $number, $file);
        }

        header('Content-Type: application/msword');
        header('Content-Disposition: attachment, filename=' . $name . '.rtf');
        return print $file;
    }

    function utf_to_cp($str) {
        return iconv('UTF-8', 'CP1251', $str);
    }

    function cp_to_utf($str) {
        return iconv('CP1251', 'UTF-8', $str);
    }

    function num2str($L) {
        global $_1_2, $_1_19, $des, $hang, $namerub, $nametho, $namemil, $namemrd, $kopeek;

        $s = " ";
        $s1 = " ";
        $s2 = " ";
        $kop = intval(($L * 100 - intval($L) * 100));
        $L = intval($L);
        if ($L >= 1000000000) {
            $many = 0;
            $this->semantic(intval($L / 1000000000), $s1, $many, 3);
            $s .= $s1 . $namemrd [$many];
            $L %= 1000000000;
        }

        if ($L >= 1000000) {
            $many = 0;
            $this->semantic(intval($L / 1000000), $s1, $many, 2);
            $s .= $s1 . $namemil [$many];
            $L %= 1000000;
            if ($L == 0) {
                $s .= "гривень ";
            }
        }

        if ($L >= 1000) {
            $many = 0;
            $this->semantic(intval($L / 1000), $s1, $many, 1);
            $s .= $s1 . $nametho [$many];
            $L %= 1000;
            if ($L == 0) {
                $s .= "гривень ";
            }
        }

        if ($L != 0) {
            $many = 0;
            $this->semantic($L, $s1, $many, 0);
            $s .= $s1 . $namerub [$many];
        }

        if ($kop > 0) {
            $many = 0;
            $this->semantic($kop, $s1, $many, 1);
            $s .= $s1 . $kopeek [$many];
        } else {
            $s .= " 00 копійок";
        }

        return $s;
    }

    function delivery() {

        $db = $this->dbconf();

        if (!MySQL::Open($db ['name'], $db ['host'], $db ['user'], $db ['pass'])) {
            MySQL::Kill ();
        }

        // MySQL::Open( $db['name'], $db['host'], $db['user'], $db['pass']) or MySQL::Error();


        $users = $_POST ['users'];
        $mess = trim($_POST ['message']);
        $title = trim($_POST ['title']);
        for ($i = 0; $i < count($users); $i++) {
            MySQL::Query('SELECT IP,RealName,Cash,Userdata0,Userdata2 FROM `users` where `login`= "' . trim($users [$i]) . '" limit 1 ');
            //MySQL::Query('SELECT IP,RealName,Cash,Userdata0,Userdata2 FROM `users` where `login`= "'.trim($users[$i]).'" limit 1 ') or MySQL::Kill();
            $user = MySQL::Row ();
            //$user = MySQL::RowArray();
            //file_put_contents('/home/morfey/1.txt',$this->koi_to_utf($user[$i]->RealName)."\n",FILE_APPEND);
            $message[$i] = preg_replace('#\{login\}#Uis', $users [$i], $mess);
            $message[$i] = preg_replace('#\{name\}#Uis', $this->koi_to_utf($user->RealName), $message[$i]);
            $message[$i] = preg_replace('#\{ip\}#Uis', $user->IP, $message[$i]);
            $message[$i] = preg_replace('#\{cash\}#Uis', $user->Cash, $message[$i]);
            $message[$i] = preg_replace('#\{ndog\}#Uis', $user->Userdata2, $message[$i]);
            $message[$i] = preg_replace('#\{mac\}#Uis', $user->Userdata0, $message[$i]);

            //$this->SendMessage ( $users [$i], $message );
            if ($_POST['message_web'] == 1) {
                $web = 1;
                $message[$i] = $message[$i];
            }
            if ($_POST['message_mail'] == 1) {
                $mail = 1;
            }
            if ($_POST['message_auth'] == 1) {
                $auth = 1;
            }



            $this->SendMessage($users[$i], $title, $message[$i], $msgver = 1, $msgtype = 1, $repeat = 0, $repeatperiod = 0, $showtime = 0, $web, $mail, $auth);
        }
    }

    function freezing($type, $user, $date_start, $date_end) {


        // Column status in databse:
        // 0 - nothing(ready to freezing)
        // 1 - Allready Freezing
        // 2 - End Freezing (UnFreezing)


        if ($type == 'set') {
            $this->db->query('delete from `Freezing` where User="' . $user . '" and Status = 0');
            $this->db->query('insert into `Freezing` (User,Date_start,Date_end) values ("' . trim($user) . '","' . $date_start . '","' . $date_end . '") ');
        }
        if ($type == 'show') {

            $query = $this->db->query('select * from `Freezing` where User="' . $user . '" and (Status = 0 or Status = 1)  order by ID desc');

            $row = $query->row();


            if ($row->ID) {
                $r ['diff'] = $this->datediff($row->Date_start, $row->Date_end);
                $r ['startdiff'] = substr($row->Date_start, 0, -8);
                $r ['enddiff'] = substr($row->Date_end, 0, -8);
                $r ['status'] = $row->Status;
            }

            $query2 = $this->db->query('select * from `Freezing` where User="' . $user . '" and Status = 2  order by ID desc');

            $row2 = $query2->row();


            if ($row2->ID) {

                // $r ['diff2'] = $this->datediff($row2->Date_start, $row2->Date_end);
                /*
                  $r ['startdiff2'] = $row2->Date_start;
                  $r ['enddiff2'] = $row2->Date_end;

                  $r ['status2'] = $row2->Status;
                 */
                // $query2 = $this->db->query('select * from `Freezing` where User="' . $user . '" and Status = 2  order by ID desc');
                $r ['count'] = $row->count;
                $i = 0;
                foreach ($query2->result_array() as $user) {

                    $un[$i] = $user;
                    //                    print $user['Date_start'];
                    $un[$i]['diff2'] = $this->datediff($user['Date_start'], $user['Date_end']);
                    $un[$i]['Date_start'] = substr($user['Date_start'], 0, -8);
                    $un[$i]['Date_end'] = substr($user['Date_end'], 0, -8);

                    ++$i;
                }


                $r['unfr'] = $un;
            }

            return $r;
        }
    }

    function datediff($date_start, $date_end) {
        $start = explode('-', $date_start);
        $end = explode('-', $date_end);
        return ( mktime(0, 0, 0, $end[1], $end[2], $end[0]) - mktime(0, 0, 0, $start[1], $start[2], $start[0])) / (60 * 60 * 24);
    }

    function getStatuses() {
        $query = $this->db->query('SELECT * FROM StatusNames order BY name ASC');
        return $query->result_array();
    }

    function getTasksUser($name) {
        $query = $this->db->query('SELECT *,sn.Name as Name FROM StatusTasks as s LEFT JOIN StatusNames as sn on s.StatusID=sn.ID  where s.User="' . $name . '" and Status = 0 ');

        $query2 = $this->db->query('SELECT *,sn.Name as Name FROM StatusTasks as s LEFT JOIN StatusNames as sn on s.StatusID=sn.ID  where s.User="' . $name . '" and Status = 1 ');

        $result = $query->result_array();

        foreach ($query2->result_array() as $value) {

            $result['history'][] = $value;
        }

        return $result;
    }

    function getTasks(){
    
        $query = $this->db->query('SELECT *,sn.Name as Name FROM StatusTasks as s LEFT JOIN StatusNames as sn on s.StatusID=sn.ID  where Status = 0 order by Date DESC');

        return $query->result();

    }

}

?>
